const express = require('express');
const { NotificationService } = require('./notificationService');
const { config } = require('./config');

const app = express();
app.use(express.json());

const svc = new NotificationService();

app.post('/notify', async (req, res) => {
  const { type, title, content, barkDeviceKeys, emailTo } = req.body || {};

  if (!title || !content) {
    return res.status(400).json({ ok: false, message: 'title 与 content 为必填' });
  }

  let channels;
  if (!type || type === 'all') channels = 'all';
  else if (['bark', 'email'].includes(type)) channels = [type];
  else return res.status(400).json({ ok: false, message: 'type 仅支持 all|bark|email' });

  const perChannel = {};
  // Bark device keys override if provided
  if (barkDeviceKeys) {
    const keys = Array.isArray(barkDeviceKeys)
      ? barkDeviceKeys
      : String(barkDeviceKeys).split(',').map(s => s.trim()).filter(Boolean);
    perChannel.bark = { deviceKeys: keys };
  } else if (config.bark.deviceKeys && config.bark.deviceKeys.length) {
    perChannel.bark = { deviceKeys: config.bark.deviceKeys };
  }

  // Email to override if provided
  if (emailTo) {
    perChannel.email = { to: Array.isArray(emailTo) ? emailTo : String(emailTo).split(',').map(s => s.trim()).filter(Boolean) };
  } else if (process.env.DEMO_EMAIL_TO) {
    perChannel.email = { to: process.env.DEMO_EMAIL_TO.split(',').map(s => s.trim()).filter(Boolean) };
  }

  try {
    const results = await svc.send({ title, body: content, text: content }, { channels, perChannel });
    return res.json({ ok: true, results });
  } catch (e) {
    return res.status(500).json({ ok: false, message: e.message, results: e.results });
  }
});

const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3002;
app.listen(PORT, () => {
  // eslint-disable-next-line no-console
  console.log(`Notification service listening on port ${PORT}`);
});


